package server

import (
	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/selector"
	"github.com/go-kratos/kratos/v2/middleware/validate"
	"github.com/go-kratos/swagger-api/openapiv2"
	"github.com/gorilla/handlers"
	v1 "phm/api/helloworld/v1"
	pb2 "phm/api/phm/v1"
	pb "phm/api/phm/v1/bigscreen"
	pw "phm/api/phm/v1/webmanage"
	"phm/auth"
	"phm/internal/service/bigscreen"
	"phm/internal/service/webmanage"
	// bigScre "phm/api/phm/v1/bigscreen"
	"phm/internal/conf"
	"phm/internal/service"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/transport/http"
)

// NewHTTPServer new an HTTP server.
func NewHTTPServer(
	authRepo auth.AuthRepo,
	userService *webmanage.UserService,
	roleService *webmanage.RoleService,
	operationService *webmanage.OperationService,
	menuService *webmanage.PermissionMenuService,
	bigscreenService *bigscreen.RadarBigscreenService,
	//
	fileService *service.FileService,
	radarService *service.RadarService,
	studentService *service.StudentService,
	greeter *service.GreeterService, logger log.Logger) *http.Server {
	var opts = []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
			logging.Server(logger),
			// auth
			//auth.PHMMiddlewareCors(),
			validate.Validator(),
			selector.Server(
				// auth.Server()
				authRepo.Server(),
			).Match(auth.NewWhiteListMatcher(whiteList)).Build(),
		),
		http.Filter(handlers.CORS( // 浏览器跨域
			handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization", "PHMToken"}),
			handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"}),
			handlers.AllowedOrigins([]string{"*"}),
		)),
	}
	if conf.Config.Server.Http.Network != "" {
		opts = append(opts, http.Network(conf.Config.Server.Http.Network))
	}
	if conf.Config.Server.Http.Addr != "" {
		opts = append(opts, http.Address(conf.Config.Server.Http.Addr))
	}
	if conf.Config.Server.Http.Timeout != nil {
		opts = append(opts, http.Timeout(conf.Config.Server.Http.Timeout.AsDuration()))
	}
	opts = append(opts, http.ResponseEncoder(auth.DefaultResponseEncoder), http.ErrorEncoder(auth.PHMDefaultErrorEncoder))
	srv := http.NewServer(opts...)
	// extension:
	srv.Route("/").POST("/pc/file/upload", fileService.UploadFile)
	//
	v1.RegisterGreeterHTTPServer(srv, greeter)
	pb2.RegisterRadarHTTPServer(srv, radarService)
	pb2.RegisterStudentHTTPServer(srv, studentService)
	//
	pw.RegisterUserHTTPServer(srv, userService)
	pw.RegisterOperationHTTPServer(srv, operationService)
	pw.RegisterRoleHTTPServer(srv, roleService)
	pw.RegisterPermissionMenuHTTPServer(srv, menuService)
	//
	pb.RegisterRadarBigscreenHTTPServer(srv, bigscreenService)
	// /q/swagger-ui/
	srv.HandlePrefix("/q/", openapiv2.NewHandler())
	return srv
}
